package com.isyscore.os.core.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.boot.login.properties.LoginProperties;
import com.isyscore.os.core.util.InitiallyUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.HashSet;
import java.util.Set;

/**
 * @author felixu
 * @since 2021.05.10
 *  metadata中超级管理员也不能导出其他租户的内容
 */
public class MetaDataTenantLineHandler implements TenantLineHandler {

    /**
     * 需要被忽略的表
     */
    private final Set<String> ignores;

    private final LoginProperties properties;

    private final LoginUserManager loginUserManager;

    public MetaDataTenantLineHandler(LoginProperties properties, LoginUserManager loginUserManager) {
        this.properties = properties;
        this.loginUserManager = loginUserManager;
        ignores = new HashSet<>(properties.getTenantIgnoreTables());
    }

    @Override
    public Expression getTenantId() {
        return new StringValue(loginUserManager.getCurrentTenantId());
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if (!properties.isEnable())
            return true;
        if (ignores.contains(tableName))
            return true;
        if (InitiallyUtils.checkInitially())
            return true;
        return false;
    }
}
